import csv
import random

from my_package import my_tools

lists = []


def random_info(n=100):
    subjects = ['java', 'html', 'python', 'css']
    names = []
    for i in range(n // len(subjects)):
        name = my_tools.random_string(random.randint(3, 6))
        names.append(name)

    for i in range(n):
        name = random.choice(names)
        subject = random.choice(subjects)
        score = random.randint(50, 100)
        for j in lists:
            # 姓名、学科不要重复
            if j[0] == name and j[1] == subject:
                break
        else:
            lists.append([name, subject, score])


# 读取
def average():
    with open('resources/data.csv', mode='r', encoding='utf-8') as f:
        cf = csv.reader(f)
        head = next(cf)  # 获取表头 => next 将cf迭代到下一步
        # print(head)
        scores = []
        for i in cf:
            if len(i) != 0:
                scores.append(int(i[2]))
        return sum(scores) / len(scores)


# 写入
def make_data():
    with open('resources/data.csv', mode='a', newline='', encoding='utf-8') as f:
        cf = csv.writer(f)
        random_info()
        cf.writerows(lists)  # 写入多行


# with open('data.csv',mode='a',encoding='utf-8') as f:
#     cf = csv.writer(f)
#     cf.writerow(['tom','js','90'])  # 单行
#     lists = [['wang','js','90'],['lili','js','55'],['bane','js','70']]
#     cf.writerows(lists)  # 写入多行

# make_data()
avg_score = average()
print("大家的平均分是", round(avg_score,1))
